package com.woniuxy.utils;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * JWT工具类
 */
@Component
@Slf4j
public class JwtUtil {

    //密钥
    private String secret = "1234";
    /**
     * 创建Token的方法
     */
    public String createToken(Map<String, Object> claims) {
        //1.创建JWT构建器，并且设置基本的参数
        JwtBuilder builder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret)  //签名
                .compressWith(CompressionCodecs.GZIP);   //指定压缩格式
        //添加多个键和值
        if (claims != null) {
            builder.setClaims(claims);
        }
        //返回字符串
        return builder.compact();
    }

    /**
     * 解析Token
     */
    public Jws<Claims> parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token);
    }

    /**
     * 获取指定的值
     */
    public String getValue(String token, String key) {
        //解析Token，判断Token是否合法
        Jws<Claims> claimsJws = parseToken(token);
        //获取载荷
        Claims claims = claimsJws.getBody();
        //获取指定的值
        return claims.get(key).toString();
    }

    /**
     * 验证JWT是否有效方法
     */
    public boolean validateToken(String token) {
        //直接调用上面的方法进行解析
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            log.info("验证Token失败:{}", e.getMessage());
            return false;
        }
    }

    /**
     * 获取IP地址的方法
     */
    public String getRequestIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
